#!/usr/bin/env bash
set -e

INPUT_VERSION="$1"

if [[ -z "$INPUT_VERSION" ]]; then
  echo "❌ 必须提供版本号参数（如 1.24 或 ^1.22）"
  exit 1
fi

VERSIONS_JSON=$(curl -sSL 'https://golang.google.cn/dl/?mode=json')
ALL_VERSIONS=$(echo "$VERSIONS_JSON" | grep -oP 'go\d+\.\d+(\.\d+)?' | sed 's/^go//' | sort -Vr)

if [[ "$INPUT_VERSION" =~ ^[0-9]+\.[0-9]+$ ]]; then
  # 输入为 1.24 → 匹配 1.24.*
  MATCH_VERSION=$(echo "$ALL_VERSIONS" | grep "^$INPUT_VERSION\." | head -n1)
elif [[ "$INPUT_VERSION" =~ ^\^([0-9]+)\.([0-9]+)$ ]]; then
  MAJOR="${BASH_REMATCH[1]}"
  MINOR="${BASH_REMATCH[2]}"
  MATCH_VERSION=$(echo "$ALL_VERSIONS" | grep "^${MAJOR}\.${MINOR}\." | head -n1)
elif [[ "$INPUT_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  MATCH_VERSION="$INPUT_VERSION"
else
  echo "❌ 不支持的版本格式：$INPUT_VERSION"
  exit 1
fi

if [[ -z "$MATCH_VERSION" ]]; then
  echo "❌ 无法从 golang.google.cn 匹配版本：$INPUT_VERSION"
  exit 1
fi

echo "$MATCH_VERSION"
